//处理token鉴权
const pool = require("../../sql/index");
const jwt = require("jsonwebtoken");

const auth = async (req, res, next) => {
  const raw = String(req.headers.authorization).split(" ").pop();
  const secretKey = require("../../util/const").secretKey;
  const { id } = jwt.verify(raw, secretKey);
  req.user = pool.getConnection(function (err, connection) {
    if (err) {
      throw err;
    }
    const sql = `select id,userName from users where id ='${id}'  limit 1;`;
    connection.query(sql, function (error, results, fields) {
      connection.release();
      return results;
    });
  });
  next();
};

module.exports = auth;
